using System;
using System.Collections.Generic;
using System.Linq;
using MyApp.WebApi.Entity;
using MyApp.WebApi.ParamModel;
using MyApp.WebApi.Repository;
using MyApp.WebApi.Utils;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;


namespace Admin3000.Backend.Controllers
{
    //订单列表
    // [Authorize]
    [ApiController]
    [Route("[controller]")]
    public class OrdersController : ControllerBase
    {
        private IRepository<Orders> _ordersRespository;
        private IRepository<Goods> _goodsRespository;
        private IRepository<OrdersSpecs> _orderSpecsRespository;
        private IRepository<Photos> _photosRespository;
        private IRepository<GoodsPhotos> _goodsPhotosRespository;

        private IRepository<Catagorys> _catagorysRespository;
        private IRepository<GoodsCatagorys> _goodsCatagorysRespository;

        private IRepository<GoodsSpecs> _goodsSpecsTypesRespository;
        private IRepository<Attributes> _attributesRespository;
        private IRepository<AttributeValues> _attributeValuesRespository;
        private IRepository<UsersOrders> _usersordersRespository;
        private IRepository<Users> _usersRespository;
        private IRepository<PayWays> _payWaysRespository;
        private IRepository<UsersGoods> _usersGoodsRespository;
        private IRepository<Comments> _commentsRespository;
        private IRepository<CommentTypes> _commentTypesRespository;
        private IRepository<Types> _typesRespository;







        private TokenParameter _tokenParameter;
        private readonly IConfiguration _configuration;

        public OrdersController(
            IConfiguration configuration,
            IRepository<Orders> ordersRespository,
            IRepository<Goods> goodsRespository,
            IRepository<OrdersSpecs> orderSpecsRespository,
            IRepository<Photos> photosRespository,
            IRepository<GoodsPhotos> goodsPhotosRespository,
            IRepository<Catagorys> catagorysRespository,
            IRepository<GoodsCatagorys> goodsCatagorysRespository,
            IRepository<GoodsSpecs> goodsSpecsTypesRespository,
            IRepository<Attributes> attributesRespository,
            IRepository<AttributeValues> attributeValuesRespository,
            IRepository<UsersOrders> usersordersRespository,
            IRepository<Users> usersRespository,
            IRepository<PayWays> payWaysRespository,
            IRepository<UsersGoods> usersGoodsRespository,
            IRepository<Comments> commentsRespository,
            IRepository<CommentTypes> commentTypesRespository,
            IRepository<Types> typesRespository




        )
        {
            _configuration = configuration;
            _ordersRespository = ordersRespository;
            _goodsRespository = goodsRespository;
            _orderSpecsRespository = orderSpecsRespository;
            _photosRespository = photosRespository;
            _goodsPhotosRespository = goodsPhotosRespository;
            _goodsCatagorysRespository = goodsCatagorysRespository;
            _catagorysRespository = catagorysRespository;
            _goodsSpecsTypesRespository = goodsSpecsTypesRespository;
            _attributesRespository = attributesRespository;
            _attributeValuesRespository = attributeValuesRespository;
            _usersordersRespository = usersordersRespository;
            _usersRespository = usersRespository;
            _payWaysRespository = payWaysRespository;
            _usersGoodsRespository = usersGoodsRespository;
            _commentsRespository = commentsRespository;
            _commentTypesRespository = commentTypesRespository;
            _typesRespository = typesRespository;


            _tokenParameter =
                _configuration
                    .GetSection("TokenParameter")
                    .Get<TokenParameter>();
        }


        //获取订单列表
        [HttpGet, Route("getlist")]
        public dynamic GetList()
        {
            var list = from orders in _ordersRespository.Table
                       join ordersSpecs in _orderSpecsRespository.Table on orders.Id equals ordersSpecs.OrdersId
                       join goods in _goodsRespository.Table on ordersSpecs.GoodsId equals goods.Id
                       join goodsphotos in _goodsPhotosRespository.Table on goods.Id equals goodsphotos.GoodsId
                       join photos in _photosRespository.Table on goodsphotos.PhotosId equals photos.Id
                       join goodscatagorys in _goodsCatagorysRespository.Table on goods.Id equals goodscatagorys.GoodsId
                       join catagorys in _catagorysRespository.Table on goodscatagorys.CatagorysId equals catagorys.Id
                       join goodspecs in _goodsSpecsTypesRespository.Table on ordersSpecs.GoodsSpecsId equals goodspecs.Id
                       join attributes in _attributesRespository.Table on goodspecs.AttributesId equals attributes.Id
                       join attributevalues in _attributeValuesRespository.Table on goodspecs.AttributeValuesId equals attributevalues.Id
                       join userorders in _usersordersRespository.Table on orders.Id equals userorders.OrdersId
                       join users in _usersRespository.Table on userorders.UsersId equals users.Id
                       join payways in _payWaysRespository.Table on userorders.PayWaysId equals payways.Id
                       join usersgoods in _usersGoodsRespository.Table on users.Id equals usersgoods.UsersId
                       join comment in _commentsRespository.Table on usersgoods.CommentsId equals comment.Id
                       join commentTypes in _commentTypesRespository.Table on comment.Id equals commentTypes.CommentsId
                       join types in _typesRespository.Table on commentTypes.TypesId equals types.Id
                       where orders.IsDeleted == false
                       select new
                       {
                           OrderId = orders.Id,
                           GoodsId = goods.Id,
                           PhotosId = photos.Id,
                           GoodsSpecsId = goodspecs.Id,
                           UsersOrdersId = userorders.Id,
                           UsersName = users.Username,
                           GoodsName = goods.GoodsName,
                           PayWay = payways.Ways,
                           Picture = photos.Picture,
                           Price = orders.Price,
                           OrderCode = orders.OrderCode,
                           TotalMoney = orders.TotalMoney,
                           Number = orders.Number,
                           CatagoryName = catagorys.CatagoryName,
                           ParentId = catagorys.ParentId,
                           AttributeName = attributes.AttributeName,
                           Values = attributevalues.Values,
                           Comment = comment.Comment,
                           CommentScore = comment.CommentScore,
                           CommentType = types.CommentType
                       };

            var res = new
            {
                Code = 200,
                Data = list,
                Msg = "获取订单列表成功!"
            };
            return res;
        }

        //订单表分页
        [HttpGet]
        public dynamic Get([FromQuery] Pager pager)
        {
            var pageIndex = pager.PageIndex;
            var pageSize = pager.PageSize;
            var rowsTotal = pager.RowsTotal;


            // 获得所有满足条件的记录
            var users =
                _ordersRespository.Table.Where(x => x.IsDeleted == false);

            //  var users = from program in _ordersRespository.Table
            //             join articleprogram in _articleRespository.Table on program.Id equals articleprogram.ProgramId
            //             orderby articleprogram.Id
            //             select new
            //             {
            //                 Id = program.Id,
            //                IsActived = program.IsActived,
            //                 IsDeleted = program.IsDeleted,
            //                 CreatedTime = program.CreatedTime,
            //                 Remarks = program.Remarks

            //             };

            // 对获得的记录分页
            var u =
                users.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();

            // 返回的数据里，带有数据和分页信息
            var res =
                new
                {
                    Code = 1000,
                    Data =
                        new
                        {
                            Data = u,
                            Pager =
                                new
                                {
                                    pageIndex,
                                    pageSize,
                                    rowsTotal = users.Count()
                                }
                        },
                    Msg = "获取订单列表成功^_^"
                };
            return res;
        }
        //获取订单表指定Id信息
        [HttpGet("{id}")]
        public dynamic Get(int id)
        {
            var AritpId = _ordersRespository.GetById(id);

            if (AritpId == null)
            {
                return new { Code = 1000, Data = "", Msg = "指定订单不存在" };
            }
            return new
            {
                Code = 1000,
                Data = AritpId,
                Msg = "获取订单列表成功^_^"
            };
        }   

        // 订单表添加
        [HttpPost]
        public string Post(NewOrders model)
        {
            // JsonSerializerSettings settings = new JsonSerializerSettings();
            // // settings.MissingMemberHandling = MissingMemberHandling.Ignore;
            // settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            var orderCode = model.OrderCode;
            var totalMoney = model.TotalMoney;
            var price = model.Price;
            var number = model.Number;


            if (
                orderCode <= 0

            )
            {
                var tmp =
                    new
                    {
                        Code = 1004,
                        Data = "",
                        Msg = "订单不能为空，请确认后重试"
                    };
                return JsonHelper.Serialize(tmp);
            }

            var user =
                new Orders
                {
                    OrderCode = model.OrderCode,
                    TotalMoney = model.TotalMoney,
                    Price = model.Price,
                    Number = model.Number
                };

            _ordersRespository.Insert(user);

            var res = new { Code = 1000, Data = user, Msg = "添加订单成功" };
            return JsonHelper.Serialize(res);
        }
        // 订单表修改指定id
        [HttpPut("{id}")]
        public dynamic Put(int id, NewOrders model)
        {
            var OrdersId = _ordersRespository.GetById(id);

            if (OrdersId != null)
            {
                OrdersId.OrderCode = model.OrderCode;
                OrdersId.TotalMoney = model.TotalMoney;
                OrdersId.Price = model.Price;
                OrdersId.Number = model.Number;
                // user.Password = model.Password;
                OrdersId.UpdatedTime = DateTime.Now;
                _ordersRespository.Update(OrdersId);
                return JsonHelper
                    .Serialize(new
                    {
                        Code = 1000,
                        Data = OrdersId,
                        Msg =
                            string
                                .Format("你修改订单的id为：{0}，已经修改成功，请注意查收",
                                id)
                    });
            }
            else
            {
                return JsonHelper
                    .Serialize(new
                    {
                        Code = 104,
                        Data = "",
                        Msg = "指定Id的订单不存在，请确认后重试"
                    });
            }
        }
        // 订单表删除
        [HttpDelete("{id}")]
        public dynamic Delete(int id)
        {
            var AritpId = _ordersRespository.GetById(id);
            if (AritpId != null)
            {
                _ordersRespository.Delete(id);
                return new
                {
                    Code = 1000,
                    Msg = string.Format("删除指定id为{0}的订单成功", id)
                };
            }
            else
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "指定Id的订单不存在，请确认后重试"
                };
            }
        }
    }
}
